package com.white.mybatis.dynamic;

import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.aop.support.AopUtils;

/**
 * <p>
 * 日志
 * </p>
 *
 * @author huangzy
 * @since 2022/3/18
 */
public class DynamicMapperLogger {

    private final Log logger;

    public DynamicMapperLogger(Class<? extends BaseDynamicMppaer> mapperClass){
        this.logger = LogFactory.getLog(mapperClass);
    }

    /**
     * 获取日志输出前缀
     * @return
     */
    private String getLogPrefix(){
        return "[DynamicMapper#"+ AopUtils.getTargetClass(this).getName() +"] ";
    }

    /**
     * 准备执行SQL的日志输出
     */
    public void logPreparing(String sql){
        logger.debug(getLogPrefix() + "==>  Preparing: "+sql);
    }

    /**
     * 准备执行SQL的参数注入日志输出
     */
    public void logParameters(Object[] param){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < param.length; i++) {
            Object obj = param[i];
            sb.append(obj);
            sb.append("(");
            sb.append(obj.getClass().getSimpleName());
            sb.append(")");
            if (i < param.length - 1){
                sb.append(", ");
            }
        }
        logger.debug(getLogPrefix() + "==> Parameters: "+ sb);
    }

    /**
     * SQL执行结果集字段日志输出
     */
    public void logColumns(String[] columns){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < columns.length; i++) {
            String column = columns[i];
            sb.append(column);
            if (i < columns.length - 1){
                sb.append(", ");
            }
        }
        logger.debug(getLogPrefix() + "<==    Columns: "+ sb);
    }

    /**
     * SQL执行结果集值日志输出
     */
    public void logRow(Object[] row){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < row.length; i++) {
            Object result = row[i];
            sb.append(result);
            if (i < row.length - 1){
                sb.append(", ");
            }
        }
        logger.debug(getLogPrefix() + "<==        Row: "+ sb);
    }

    /**
     * SQL执行结果集数量日志输出
     */
    public void logTotal(long total){
        logger.debug(getLogPrefix() + "<==      Total: "+ total);
    }

}
